package com.aistar.service.impl;

import com.aistar.mapper.*;
import com.aistar.pojo.*;
import com.aistar.pojo.pojoOV.OrderDetailOV;
import com.aistar.pojo.pojoOV.ProductOrderOV;
import com.aistar.service.ProOrderService;
import com.aistar.util.LeeJSONResult;
import com.aistar.util.OrderStatusEnum;
import com.aistar.util.ServerResponse;
import com.fasterxml.jackson.annotation.JsonFormat;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class ProOrderServiceImpl implements ProOrderService {

    @Autowired
    private ProOrderMapper proOrderMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private FlowMapper flowMapper;
    @Autowired
    private TripperMapper tripperMapper;
    @Autowired
    private TravellerMapper travellerMapper;

    // 修改订单状态，改为 支付成功，已付款; 同时新增支付流水
    //  orderId:订单编号   alpayFlowNum：支付宝交易号    paidAmount：支付金额
    @Override
    public void updateOrderStatus(String orderId,String alpayFlowNum, String paidAmount) {
        ProOrder order = (ProOrder)getById(Integer.valueOf(orderId)).getData();
        if (order.getOrderStatus().equals(OrderStatusEnum.WAIT_PAY.value)) {
            order.setOrderStatus(OrderStatusEnum.PAID.value);
            order.setOrderMoney(Float.valueOf(paidAmount));
            //先修改订单状态
            proOrderMapper.updateByPrimaryKeySelective(order);


            String flowId = UUID.randomUUID().toString().replace("-","");
            Flow flow = new Flow();
            flow.setId(flowId);
            flow.setFlowNum(alpayFlowNum);
            flow.setBuyCounts(1);
            flow.setCreateTime(new Date());
            flow.setOrderNum(orderId);
            flow.setPaidAmount(paidAmount);
            flow.setPaidMethod(1);
            flow.setProductId(order.getProductId().toString());
            //添加流水
            Integer rows = flowMapper.insertSelective(flow);
            System.out.println("新建流水===rows:"+rows);
        }
    }

    @Override
    public ServerResponse getById(Integer id) {
        ProOrder proOrder = proOrderMapper.selectByPrimaryKey(id);
        if (proOrder!=null)
            return  ServerResponse.getDataSuccess(proOrder);
        return ServerResponse.getDataFailed("没有数据！");
    }

    @Override
    public ServerResponse getAllOrder(Integer customerId, Integer pageNum) {

        List<ProductOrderOV> productOrderOVList = new ArrayList<>();

//        1.先根据用户id找到所有订单 ，分页
//        OrderExample orderExample = new OrderExample();
//        orderExample.createCriteria().andCustomerIdEqualTo(cusId);
        ProOrderExample proOrderExample = new ProOrderExample();
        proOrderExample.createCriteria().andCustomerIdEqualTo(customerId);

        List<ProOrder> orderList = proOrderMapper.selectByExample(proOrderExample);

//        Page<ProOrder> orderPage = PageHelper.startPage(pageNum, 3);
//        PageInfo pageInfo = orderPage.toPageInfo();

//        2.循环封装ProductOrderOV
        orderList.forEach(order -> {
            Product product = productMapper.selectByPrimaryKey(order.getCustomerId());
            ProductOrderOV productOrderOV = new ProductOrderOV(product, order);
            productOrderOVList.add(productOrderOV);

        });
//        3.封装pageInfo
//        pageInfo.setList(productOrderOVList);
//        System.out.println(pageInfo);

        if (orderList != null && orderList.size() > 0)
            return ServerResponse.getDataSuccess(productOrderOVList);
        else
            return ServerResponse.getDataFailed(productOrderOVList);
    }

    @Override
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public ServerResponse getAll(Integer customerId) {
        List<ProductOrderOV> productOrderOVList = new ArrayList<>();

        ProOrderExample proOrderExample = new ProOrderExample();
        proOrderExample.createCriteria().andCustomerIdEqualTo(customerId);

        List<ProOrder> orderList = proOrderMapper.selectByExample(proOrderExample);

//            Page<ProOrder> orderPage = PageHelper.startPage(1,3);
//            PageInfo pageInfo = orderPage.toPageInfo();

//        2.循环封装ProductOrderOV
        orderList.forEach(order -> {
            Product product = productMapper.selectByPrimaryKey(order.getProductId());
            ProductOrderOV productOrderOV = new ProductOrderOV(product, order);
            productOrderOVList.add(productOrderOV);

        });
//        3.封装pageInfo
//            pageInfo.setList(productOrderOVList);
//            System.out.println(pageInfo);

        if (orderList != null && orderList.size() > 0)
            return ServerResponse.getDataSuccess(productOrderOVList);
        else
            return ServerResponse.getDataFailed(productOrderOVList);
    }

    @Override
    public ServerResponse addOrder(ProOrder proOrder) {
        int row = proOrderMapper.insert(proOrder);
        if (row >= 1) {
            return ServerResponse.addSuccess();
        } else {
            return ServerResponse.addFailed();
        }

    }

//    获得新订单的Id
    @Override
    public ServerResponse getNewOrderId() {
        ProOrderExample example = new ProOrderExample();
        ProOrderExample.Criteria criteria = example.createCriteria();
        criteria.getAllCriteria();
        example.setOrderByClause("id desc");
        List<ProOrder> orderList = proOrderMapper.selectByExample(example);

        if (orderList != null && orderList.size() != 0) {
            Integer newID = orderList.get(0).getId()+1;
            return ServerResponse.getDataSuccess(newID);
        } else {
            //没有订单 返回第一个订单id  1001
            return ServerResponse.getDataSuccess(1001);
        }

    }

    /**
     * 获得订单详情
     * @param orderId 订单id
     * @param proId  产品id
     * @return
     */
    @Override
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public ServerResponse getOrderDetail(Integer orderId, Integer proId) {

        //1、根据订单id获得订单对象
        ProOrder order = proOrderMapper.selectByPrimaryKey(orderId);

        //2、根据产品id获得蟾皮对象
        Product product = productMapper.selectByPrimaryKey(proId);

        //3、根据订单id获得订单流水对象 ： 一个订单对应一个流水号，不存在一对多
        FlowExample flowExample = new FlowExample();
        flowExample.createCriteria().andOrderNumEqualTo(Integer.toString(orderId));

        List<Flow> flowMappers = new ArrayList<>();
        flowMappers = flowMapper.selectByExample(flowExample);
        Flow flow = flowMappers.get(0);

        //4、根据订单id找到对应的出行游客
        TripperExample tripperExample = new TripperExample();
        tripperExample.createCriteria().andOrderIdEqualTo(orderId);

        List<Tripper> trippers = new ArrayList<>();
        trippers = tripperMapper.selectByExample(tripperExample);

        //5、遍历出行游客List，根据旅客id获对应的出行旅客信息，添加到旅客信息List中
        List<Traveller> travellers = new ArrayList<>();

        trippers.forEach(tripper -> {

            Integer travelerId = tripper.getTravellerId();
            Traveller traveller = travellerMapper.selectByPrimaryKey(travelerId);
            travellers.add(traveller);
        });

        //6、封装OrderDetailOV对象，返回ServerResponse
        OrderDetailOV orderDetailOV = new OrderDetailOV(flow,order,travellers,product);

        if(orderDetailOV != null)
            return ServerResponse.getDataSuccess(orderDetailOV);
        else
            return ServerResponse.getDataFailed(orderDetailOV);

    }

}

